package com.ljx.recruitment.datapatch.strategy;

import com.ljx.recruitment.common.datapatch.DataPatchPriority;
import com.ljx.recruitment.common.datapatch.DataPatchStrategy;
import com.ljx.recruitment.security.util.UserUtil;
import com.ljx.recruitment.user.domain.entity.Role;
import com.ljx.recruitment.user.domain.entity.User;
import com.ljx.recruitment.user.domain.vo.req.RoleToUserReq;
import com.ljx.recruitment.user.domain.vo.resp.TenantResp;
import com.ljx.recruitment.user.enums.CommonRoleEnum;
import com.ljx.recruitment.user.service.RoleService;
import com.ljx.recruitment.user.service.TenantService;
import com.ljx.recruitment.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.Arrays;
import java.util.Objects;

@Component
public class InitPlatformUserDataPatch implements DataPatchStrategy {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private TenantService tenantService;

    @Override
    public String getName() {
        return "Init-Platform-User-DataPatch";
    }

    @Override
    public String getVersion() {
        return "20250225-v1";
    }

    @Override
    public Integer getSort() {
        return DataPatchPriority.LOW;
    }

    @Override
    public void run() {
        saveUserIfNotExist("anonymous", null);
        allocationToUserRole("anonymous", CommonRoleEnum.getAnonymousCode(CommonRoleEnum.PLATFORM.getKey()));
        saveUserIfNotExist("platform", "platform");
        allocationToUserRole("anonymous", CommonRoleEnum.getAdminCode(CommonRoleEnum.PLATFORM.getKey()));
    }

    private void allocationToUserRole(String userName, String roleName) {
        Role role = roleService.getByName(roleName);
        TenantResp platform = tenantService.getInfoByCode(CommonRoleEnum.PLATFORM.getKey());
        User user = userService.getByUsernameAndTenant(userName, platform.getId());
        roleService.deleteUserRole(user.getId());
        roleService.insertUserRole(user.getId(), role.getId());
    }

    private void saveUserIfNotExist(String username, String password) {
        TenantResp platform = tenantService.getInfoByCode(CommonRoleEnum.PLATFORM.getKey());
        User user = userService.getByUsernameAndTenant(username, platform.getId());
        if (Objects.nonNull(user)) {
            return;
        }
        user = new User(username, Objects.isNull(password) ? null : DigestUtils.md5DigestAsHex(password.getBytes()), platform.getId());
        userService.save(user);
    }

}
